package cn.pconline.autoclub.web.admin;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubAddress;
import cn.pconline.autoclub.entity.ClubBrand;
import cn.pconline.autoclub.entity.ClubDispose;
import cn.pconline.autoclub.entity.ClubForum;
import cn.pconline.autoclub.entity.ClubIntegral;
import cn.pconline.autoclub.entity.ClubLevel;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.ClubNotice;
import cn.pconline.autoclub.entity.Theme;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.AppConfigService;
import cn.pconline.autoclub.service.ClubBrandService;
import cn.pconline.autoclub.service.ClubLevelService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.PagerService;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.autoclub.service.ThemeService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Pinyin4jUtil;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.RegionUtil;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.WhoisUtil;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.gelivable.auth.entity.GeliSession;
import org.gelivable.auth.entity.GeliUser;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.GeliUtils;
import org.gelivable.dao.SqlBuilder;
import org.gelivable.log.GeliLogFacade;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;
import org.gelivable.web.HttpMethod;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author chensy
 */
@Controller
@RequestMapping("/admin")
public class AdminClubController {

    private static final Logger log = LoggerFactory.getLogger(AdminClubController.class);
    @Autowired
    private ClubService clubService;
    @Autowired
    private UserService userService;
    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private ClubLevelService clubLevelService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private PagerService pagerService;
    @Autowired
    private PetrolService petrolService;
    @Autowired
    private ThemeService themeService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private ClubBrandService clubBrandService;
    @Autowired
    private AppConfigService appConfigService;
    private void errorMsg(String msg, HttpServletResponse resp) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", 300)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }

    private void successMsg(String msg, String navTabId, HttpServletResponse resp) {
        try {
            String rs = StringUtils.isEmpty(msg) ? "操作成功" : msg;
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(new JSONBuilder()
                    .put("statusCode", 200)
                    .put("message", rs)
                    .put("navTabId", navTabId)
                    .toString());
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }

    private void successMsg(String msg, String navTabId, HttpServletResponse resp, String callbackType) {
        try {
            String rs = StringUtils.isEmpty(msg) ? "操作成功" : msg;
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(new JSONBuilder()
                    .put("statusCode", 200)
                    .put("message", rs)
                    .put("navTabId", navTabId)
                    .put("callbackType", callbackType)
                    .toString());
        } catch (IOException ex) {
            log.error("set successMsg fail!", ex);
        }
    }

    /**
     * 用户填写拒绝理由的页面
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/rejectMsg.do")
    public String rejectMsg(HttpServletRequest req, HttpServletResponse resp) {
        int status = WebUtils.paramInt(req, "status", -1);
        String[] idStr = WebUtils.param(req, "ids", "").split(",");
        List<Club> clubs = new ArrayList<Club>(idStr.length);
        for (String id : idStr) {
            try {
                Club c = clubService.getClub(Long.parseLong(id));
                if (c != null) {
                    clubs.add(c);
                }
            } catch (java.lang.NumberFormatException e) {
                continue;
            }
        }
        req.setAttribute("clubs", clubs);
        req.setAttribute("tmpl", MessageService.REFUSED_CLUB);
        req.setAttribute("status", status);
        req.setAttribute("defReason", MessageService.REFUSED_CLUB_DEF_REASON);
        return "admin/club/rejectMsg";
    }

    /**
     * 车友会审核列表，按申请时间降序排序
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/applyList.do")
    public String applyList(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        //param
        String name = env.param("name", "").trim();
        String area = env.param("area", "").trim();//provinceName or cityName
        String brand = env.param("brand", "").trim();//brandName
        String begin = env.param("beginDate", "");
        String end = env.param("endDate", "");
        long region = env.paramLong("region", 0);
        int status = env.paramInt("status", Club.STATUS_UNAUDITED);
        int pageNum = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 20);
        int disposeStatus = env.paramInt("dispose", -1);
        //sql
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select * from ").appendSql(geliOrm.getTableName(Club.class)).appendSql(" where 1=1 ");
        if (StringUtils.isEmpty(name) == false) {
            sql.appendSql(" and name like ").appendValue("%" + name + "%");
        }
        if (StringUtils.isEmpty(area) == false) {
            sql.appendSql(" and (province_name like ").appendValue("%" + area + "%");
            sql.appendSql(" or city_name like ").appendValue("%" + area + "%").appendSql(")");
        }
        if (StringUtils.isEmpty(brand) == false) {
            sql.appendSql(" and brand_name =").appendValue(brand);
        }
        if (StringUtils.isNotBlank(begin)) {
            sql.appendSql(" and create_at >=").appendValue(begin);
        }
        if (StringUtils.isNotBlank(end)) {
            sql.appendSql(" and create_at <=").appendValue(end);
        }
        if (region > 0) {
            if (region == 8) {
                //港澳台--目前不支持台湾
                sql.appendSql(" and province_id in (810000,820000,710000)");
            } else {
                sql.appendSql(" and region_id =").appendValue(region);
                sql.appendSql(" and province_id not in (810000,820000,710000)");
            }
        }
        if (disposeStatus > -1) {
            sql.appendSql(" and club_id in ( select club_id from ").appendSql(geliOrm.getTableName(ClubDispose.class))
                    .appendSql(" where status=").appendValue(disposeStatus).appendSql(" )");
        }
        sql.appendSql(" and status = ").appendValue(status);

        sql.appendSql(" order by create_at desc");
        //query
        Pager<Club> pager = pagerService.pager(Club.class, sql, pageNum, pageSize);

        for (Club c : pager.getResultList()) {
            c.setAddress(clubService.getAddress(c.getClubId()));
            c.setClubDispose(clubService.getClubDispose(c.getClubId()));
            c.setTheme(themeService.findThemeById(c.getThemeId()));
        }
        //return
        req.setAttribute("pager", pager);
        req.setAttribute("name", name);
        req.setAttribute("area", area);
        req.setAttribute("brand", brand);
        req.setAttribute("beginDate", begin);
        req.setAttribute("endDate", end);
        req.setAttribute("status", status);
        req.setAttribute("region", region);
        req.setAttribute("disposeStatus", disposeStatus);
        req.setAttribute("statusDesc", Club.statusDesc);

        return "admin/club/applyList";
    }

    /**
     * 批量修改状态
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/club/editStatus.do")
    public String updateStatus(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Env env = EnvUtils.getEnv();
        GeliLogFacade.log();
        HttpMethod method = env.getHttpMethod();
        if (!method.equals(HttpMethod.POST)) {
            errorMsg("非法请求", resp);
            return null;
        }
        String[] ids = req.getParameterValues("ids");
        int status = env.paramInt("status", 0);
        if (GeliSession.getCurrentUser() == null) {
            errorMsg("管理员信息已失效，请重新登录", resp);
            return null;
        }
        String rejectMsg = WebUtils.param(req, "rejectMsg", "").trim();
        if (status == Club.STATUS_REJECTED && StringUtils.isBlank(rejectMsg)) {
            errorMsg("请输入拒绝理由", resp);
            return null;
        }
        int MAX_LENGTH = 50;
        if (status == Club.STATUS_REJECTED && rejectMsg.length() > MAX_LENGTH) {
            errorMsg("自定义理由最长只允许" + MAX_LENGTH + "个字符", resp);
            return null;
        }
        long adminId = GeliSession.getCurrentUser().getUserId();
        int errorCount = 0;
        String errorMsg = "";
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                Club club = clubService.getClub(Long.parseLong(id));
                if (club != null) {
                    boolean rs = false;
                    if (club.getStatus() == Club.STATUS_UNAUDITED && status == Club.STATUS_PASS) {
                        rs = clubService.passClub(club, adminId);
                        if (!rs) {
                            log.warn("{} pass club[{}]!ip[{}]",adminId,id,WhoisUtil.getIp(req));
                            errorMsg = String.format("用户加入车友会已达到限制个数（ %s）", systemConfig.getJoinClubLimit());
                        }
                        //审核通过才创建车友会品牌
                        if(club.getBrandId() > 0 && !StringUtils.isEmpty(club.getBrandName())){
                        	    ClubBrand clubBrand = new ClubBrand();
                                clubBrand.setBrandId(club.getBrandId());
                                clubBrand.setBrandName(club.getBrandName());
                          	    String initial = Pinyin4jUtil.getPinyinToUpperCase(club.getBrandName());
                  	    	    if(initial.length()>1){
                 	    		 initial = initial.substring(0, 1);
                 	    	    }
                 	    	   initial = Pinyin4jUtil.specialHandling(club.getBrandName(), initial);
                 	    	   clubBrand.setInitial(initial);
                 	    	   
                 	    	   clubBrandService.updateClubBrand(clubBrand);
                        }
                    } else if (club.getStatus() == Club.STATUS_REJECTED && status == Club.STATUS_PASS) {
                        rs = clubService.passClub(club, adminId);
                        if (!rs) {
                            log.warn("{} re pass club[{}]!ip[{}]",adminId,id,WhoisUtil.getIp(req));
                            errorMsg = String.format("用户加入车友会已达到限制个数（ %s）", systemConfig.getJoinClubLimit());
                        }
                    } else if (club.getStatus() == Club.STATUS_LOCK && status == Club.STATUS_PASS) {
                        rs = clubService.unlockClub(club, adminId);
                    } else if (club.getStatus() == Club.STATUS_SEALED && status == Club.STATUS_PASS) {
                        rs = clubService.unsealClub(club, adminId);
                    } else if (club.getStatus() == Club.STATUS_UNAUDITED && status == Club.STATUS_REJECTED) {
                        rs = clubService.rejectClub(club, adminId, rejectMsg);
                    } else if (club.getStatus() == Club.STATUS_PASS && status == Club.STATUS_LOCK) {
                        rs = clubService.lockClub(club, adminId);
                    } else if (club.getStatus() == Club.STATUS_PASS && status == Club.STATUS_SEALED) {//页面没有入口
                        rs = clubService.sealClub(club, adminId);
                    }
                    if (!rs) {
                        errorCount++;
                    }
                }
            }
        } else {
            errorMsg("请选择要修改的车友会", resp);
            return null;
        }
        // 当操作数据条数大于1时,有失败返回失败条数
        if (ids.length > 1 && errorCount > 0) {
            successMsg("修改成功:" + (ids.length - errorCount) + "条,失败:" + errorCount + "条", "list-club-audit", resp);
            return null;
        } else if (ids.length > 1 && errorCount == 0) {
            successMsg("修改成功", "list-club-audit", resp);
            return null;
        } else if (ids.length == 1) {
            if (errorCount > 0) {
                errorMsg(errorMsg.equals("") ? "操作有误" : errorMsg, resp);
            } else {
                String closeCurrent = "";
                if (status == Club.STATUS_REJECTED) {
                    closeCurrent = "closeCurrent";
                }
                successMsg("修改成功", "list-club-audit", resp, closeCurrent);
            }

        }
        return null;
    }

    /**
     * 删除已拒绝车友会
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/club/remove.do")
    public String remove(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Env env = EnvUtils.getEnv();
        GeliLogFacade.log();
        HttpMethod method = env.getHttpMethod();
        if (!method.equals(HttpMethod.POST)) {
            errorMsg("非法请求", resp);
            return null;
        }
        String[] ids = req.getParameterValues("ids");
        if (GeliSession.getCurrentUser() == null) {
            errorMsg("管理员信息已失效，请重新登录", resp);
            return null;
        }
        long adminId = GeliSession.getCurrentUser().getUserId();
        Map<Object, String> isSuccess = new HashMap<Object, String>();
        int errorCount = 0;
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                Map<Object, String> map = clubService.removeClub(Long.parseLong(id), adminId);
                isSuccess.putAll(map);
                if (map.containsKey(false)) {
                    errorCount++;
                }
            }
        } else {
            errorMsg("请选择要删除的车友会", resp);
            return null;
        }
        // 当操作数据条数大于1时,有失败返回失败条数
        if (ids.length > 1 && errorCount > 0) {
            if (ids.length == errorCount) {
                errorMsg(isSuccess.get(false), resp);
                return null;
            }
            successMsg("删除成功:" + (ids.length - errorCount) + "条,失败:" + errorCount + "条", "list-club-audit", resp);
            return null;
        } else if (ids.length > 1 && errorCount == 0) {
            successMsg("删除成功", "list-club-audit", resp);
            return null;
        } else if (ids.length == 1) {
            if (errorCount > 0) {
                errorMsg(isSuccess.get(false), resp);
            } else {
                successMsg("删除成功", "list-club-audit", resp);
            }
        }
        return null;
    }

    /**
     * 车友会查询（已经审核通过的）
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/list.do")
    public String list(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        //param
        String orderField = env.param("orderField", "audit_at");
        String orderDirection = env.param("orderDirection", "desc");
        String name = env.param("name", "").trim();
        String area = env.param("area", "").trim();//provinceName or cityName
        String brand = env.param("brand", "").trim();
        String series = env.param("series", "").trim();
        String beginDate = env.param("beginDate", "");
        String endDate = env.param("endDate", "");
        long clubId = env.paramLong("clubId", 0);
        String clubUrl = env.param("clubUrl", "");
        long levelId = env.paramLong("levelId", -1);
        int pageNo = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 20);
        int region = env.paramInt("region", 0);
        //sql
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select club_id from ").appendSql(geliOrm.getTableName(Club.class)).appendSql(" where 1=1 ");
        if (clubId > 0) {
            sql.appendSql(" and club_id = ").appendValue(clubId);
        }
        if (StringUtils.isNotBlank(clubUrl)) {
            sql.appendSql(" and club_url = ").appendValue(clubUrl);
        }
        if (StringUtils.isNotBlank(name)) {
            sql.appendSql(" and name like ").appendValue("%" + name + "%");
        }
        if (StringUtils.isNotBlank(area)) {
            sql.appendSql(" and (province_name like ").appendValue("%" + area + "%");
            sql.appendSql(" or city_name like ").appendValue("%" + area + "%").appendSql(")");
        }
        if (StringUtils.isNotBlank(brand)) {
            sql.appendSql(" and brand_name like ").appendValue("%" + brand + "%");
        }
        if (StringUtils.isNotBlank(series)) {
            sql.appendSql(" and series_name like ").appendValue("%" + series + "%");
        }
        if (region > 0) {
            if (region == 8) {
                //港澳台--目前不支持台湾
                sql.appendSql(" and province_id in (810000,820000,710000)");
            } else {
                sql.appendSql(" and region_id =").appendValue(region);
                sql.appendSql(" and province_id not in (810000,820000,710000)");
            }
        }
        if (levelId != -1) {
            sql.appendSql(" and level_id =").appendValue(levelId);
        }
        if (StringUtils.isNotBlank(beginDate)) {
            sql.appendSql(" and create_at >=").appendValue(beginDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            sql.appendSql(" and create_at <=").appendValue(endDate);
        }
        sql.appendSql(" and status = ").appendValue(Club.STATUS_PASS);
        sql.appendSql(" order by ").appendSql(geliOrm.getColumnByField(Club.class, orderField)).appendSql(" ").appendSql(orderDirection);
        Pager<Club> pager = pagerService.pager(Club.class, sql, pageNo, pageSize);
        //petrol
        for (Club c : pager.getResultList()) {
            try {
                //设置等级对象
                c.setLevel(clubLevelService.getById(c.getLevelId()));
                //设置主题对象
                if (c.getThemeId() > 0) {
                    c.setTheme(themeService.findThemeById(c.getThemeId()));
                }
            } catch (Exception e) {
                log.error("list club failed! clubId = " + c.getClubId());
            }

        }

        //return
        req.setAttribute("pager", pager);
        req.setAttribute("name", name);
        req.setAttribute("area", area);
        req.setAttribute("brand", brand);
        req.setAttribute("series", series);
        req.setAttribute("clubId", clubId);
        req.setAttribute("clubUrl", clubUrl);
        req.setAttribute("orderField", orderField);
        req.setAttribute("orderDirection", orderDirection);
        req.setAttribute("beginDate", beginDate);
        req.setAttribute("endDate", endDate);
        req.setAttribute("region", region);
        List<ClubLevel> levels = clubLevelService.getAllLevels();
        req.setAttribute("levels", levels);
        req.setAttribute("levelId", levelId);
        return "admin/club/list";
    }

    /**
     * 车友会查询结果导出（已经审核通过的）
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/listBatchExport.do", produces = {"application/octet-stream"})
    public void listBatchExport(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        //param
        String orderField = env.param("orderField", "audit_at");
        String orderDirection = env.param("orderDirection", "desc");
        String name = env.param("name", "").trim();
        String area = env.param("area", "").trim();//provinceName or cityName
        String brand = env.param("brand", "").trim();
        String series = env.param("series", "").trim();
        String beginDate = env.param("beginDate", "");
        String endDate = env.param("endDate", "");
        long clubId = env.paramLong("clubId", 0);
        String clubUrl = env.param("clubUrl", "");
        long levelId = env.paramLong("levelId", -1);
        int pageNo = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 1000);
        //sql
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select club_id from ").appendSql(geliOrm.getTableName(Club.class)).appendSql(" where 1=1 ");
        if (clubId > 0) {
            sql.appendSql(" and club_id = ").appendValue(clubId);
        }
        if (StringUtils.isNotBlank(clubUrl)) {
            sql.appendSql(" and club_url = ").appendValue(clubUrl);
        }
        if (StringUtils.isNotBlank(name)) {
            sql.appendSql(" and name like ").appendValue("%" + name + "%");
        }
        if (StringUtils.isNotBlank(area)) {
            sql.appendSql(" and (province_name like ").appendValue("%" + area + "%");
            sql.appendSql(" or city_name like ").appendValue("%" + area + "%").appendSql(")");
        }
        if (StringUtils.isNotBlank(brand)) {
            sql.appendSql(" and brand_name like ").appendValue("%" + brand + "%");
        }
        if (StringUtils.isNotBlank(series)) {
            sql.appendSql(" and series_name like ").appendValue("%" + series + "%");
        }
        if (levelId != -1) {
            sql.appendSql(" and level_id =").appendValue(levelId);
        }
        if (StringUtils.isNotBlank(beginDate)) {
            sql.appendSql(" and create_at >=").appendValue(beginDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            sql.appendSql(" and create_at <=").appendValue(endDate);
        }
        sql.appendSql(" and status = ").appendValue(Club.STATUS_PASS);
        sql.appendSql(" order by ").appendSql(geliOrm.getColumnByField(Club.class, orderField)).appendSql(" ").appendSql(orderDirection);

        String[] cellString = new String[]{"车友会id", "名称", "简介", "品牌名称", "车系名称", "创建者", "创建时间", "会长名称", "等级", "认证人数", "会员人数", "省份名称", "城市名称", "主题帖总数", "回复总数", "总油值", "全国排名", "自定义域名", "分区名称", "品牌排名"};
        HSSFWorkbook work = new HSSFWorkbook();
        HSSFSheet sheet = work.createSheet("车友会查询列表");
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < cellString.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(cellString[i]);
        }
        Pager<Club> pager = pagerService.pager(Club.class, sql, pageNo, pageSize);
        /**
         * 根据分页数据生成excel文件
         */
        for (int curPage = pageNo; curPage <= pager.getPageCount(); curPage++) {
            // 数据一页一页加载
            if (curPage != pageNo) {
                pager = pagerService.pager(Club.class, sql, curPage, pageSize);
            }
            //petrol
            for (int i = 0; i < pager.getResultList().size(); i++) {
                Club c = pager.getResultList().get(i);
                //这里不显示实时的油值，直接用club下的totalPetrol 不然排序不方便
                //c.setPetrol(geliDao.find(ClubPetrol.class, c.getClubId()));
                c.setLevel(geliDao.find(ClubLevel.class, c.getLevelId()));
                HSSFRow rowData = sheet.createRow(((curPage - 1) * pageSize) + i + 1);
                rowData.createCell(0).setCellValue(c.getClubId());
                rowData.createCell(1).setCellValue(c.getName());
                rowData.createCell(2).setCellValue(c.getIntroduce());
                rowData.createCell(3).setCellValue(c.getBrandName());
                rowData.createCell(4).setCellValue(c.getSeriesName());
                rowData.createCell(5).setCellValue(userService.findUser(c.getCreateBy()).getUsername());
                rowData.createCell(6).setCellValue(DateUtils.formatDetail(c.getCreateAt()));
                User adminUser = userService.findUser(c.getAdminId());
                rowData.createCell(7).setCellValue(adminUser == null ? "" : adminUser.getUsername());
                rowData.createCell(8).setCellValue(c.getLevel().getLevelName());
                rowData.createCell(9).setCellValue(c.getVipNum());
                rowData.createCell(10).setCellValue(c.getMemberNum());
                rowData.createCell(11).setCellValue(c.getProvinceName());
                rowData.createCell(12).setCellValue(c.getCityName());
                rowData.createCell(13).setCellValue(c.getTopicNum());
                rowData.createCell(14).setCellValue(c.getReplyNum());
                rowData.createCell(15).setCellValue(c.getTotalPetrol());
                rowData.createCell(16).setCellValue(c.getRank());
                rowData.createCell(17).setCellValue(c.getClubUrl());
                rowData.createCell(18).setCellValue(c.getRegionName());
                rowData.createCell(19).setCellValue(c.getBrandRank());
            }
        }
        try {
            //设置返回数据类型
            resp.setContentType("application/vnd.ms-excel;charset=GBK");
            //设置返回的文件名
            resp.setHeader("Content-Disposition",
                    "attachment;Filename=autoClubList.xls");
            OutputStream out = resp.getOutputStream();
            work.write(out);
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("listBatchExport fail!", ex);
        }
    }

    /**
     * 车友会查询跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/detail.do")
    public String clubDetail(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long clubId = env.paramLong("clubId", 0);
        Club club = clubService.getClub(clubId);
        ClubNotice notice = null;
        if (club != null) {
            notice = clubService.getNotice(clubId);
        }
        List<ClubMember> listMember = memberService.listMemberByClubId(clubId);
        List<ClubForum> listForum = clubService.getForumList(clubId);
        List<Theme> listThemes = themeService.listAllThemes();
        //return
        req.setAttribute("club", club);
        req.setAttribute("notice", notice);
        req.setAttribute("listMember", listMember);
        req.setAttribute("listForum", listForum);
        req.setAttribute("listThemes", listThemes);
        return "admin/club/clubDetail";
    }

    /**
     * 车友会删除会员
     *
     * @param req
     * @param resp type=1 申请中的信息 type = 2 会员信息
     * @return
     */
    @RequestMapping(value = "/club/memberDelete.do")
    public String memberDelete(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        GeliLogFacade.log();
        long memberId = env.paramLong("id", 0);
        int type = env.paramInt("type", 0);
        long adminId = GeliSession.getCurrentUser().getUserId();
        long i = memberService.removeMemberByEdit(type, adminId, memberId);
        if (i > 0) {
            successMsg("删除成功", "club-detail", resp);
        } else {
            errorMsg("删除失败", resp);
        }
        return null;
    }

    /**
     * 车友会资料修改
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/updateSave.do")
    public String updateSave(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        GeliLogFacade.log();
        long adminId = GeliSession.getCurrentUser().getUserId();
        long clubId = env.paramLong("clubId", 0);
        String name = env.param("name", "").trim();
        long cityId = env.paramInt("cityId", 0);
        String cityName = env.param("cityName", "").replaceAll("├", "").replaceAll("└", "");
        long provinceId = env.paramInt("provinceId", 0);
        String provinceName = env.param("provinceName", "").replaceAll("请选择省份", "");
        long brandId = env.paramInt("brandId", 0);
        String brandName = env.param("brandName", "").replaceAll("请选择品牌", "");
        String qqGroup = env.param("qqGroup", "");
        if (StringUtils.isNotBlank(brandName)) {
            brandName = brandName.substring(2, brandName.length());
        }
        long seriesId = env.paramInt("seriesId", 0);
        String seriesName = env.param("seriesName", "");
        String introduce = env.param("introduce", "").trim();
        String content = env.param("content", "").trim();
        int changePetrol = env.paramInt("changePetrol", 0);
        long themeId = env.paramLong("themeId", 0);
        String retMsg = "修改成功";
        if (changePetrol != 0) {
            ClubIntegral i = petrolService.getById(PetrolService.ADD_CLUB_PETROL_ITEM_OPERATION);
            petrolService.addToClubWithinLimit(clubId, i.getIntegralId(), changePetrol, i.getName() + "(" + changePetrol + ")", false);
        }

        Club club = clubService.getClub(clubId);
        ClubNotice notice = clubService.getNotice(clubId);
        if (club != null) {
            if (!name.equals(club.getName())) {
                club.setName(name);
                String retName = clubService.checkClubName(name);
                if (!retName.equals("true")) {
                    errorMsg(retName, resp);
                    return null;
                }
            }
            if (provinceId > 0) {//只要有省份，分区都可以再更新一次
                long regionId = RegionUtil.getRegionId(provinceId);
                club.setRegionId(regionId);
                club.setRegionName(RegionUtil.getRegionName(regionId));
            }
            if ((provinceId > 0 || cityId > 0) || (brandId > 0 || seriesId > 0) || themeId>0) {
                if (cityId != club.getCityId() || provinceId != club.getProvinceId()) {
                    club.setProvinceId(provinceId);
                    club.setProvinceName(provinceName);
                    club.setCityId(cityId);
                    club.setCityName(cityName);
                }
                if (seriesId != club.getSeriesId() || brandId != club.getBrandId()) {
                    club.setSeriesId(seriesId);
                    club.setSeriesName(seriesName);
                    club.setBrandId(brandId);
                    club.setBrandName(brandName);
                }
            } else{
            	 errorMsg("地区、品牌和主题必选一个！", resp);
            	 return null;
            }
            if (!introduce.equals(club.getIntroduce())) {
                if (StringUtils.isBlank(introduce)) {
                    errorMsg("请输入车友会简介", resp);
                    return null;
                } else if (introduce.length() > 45) {
                    errorMsg("车友会简介最多45个汉字", resp);
                    return null;
                }
                club.setIntroduce(introduce);
            }
            if (!content.equals(notice.getContent())) {
                //更新公告
                if (StringUtils.isBlank(content)) {
                    errorMsg("公告不能为空", resp);
                    return null;
                } else if (StringUtil.length(content) > 100) {
                    errorMsg("公告最多50个汉字或100个字符（字母、数字）", resp);
                    return null;
                } else {
                    clubService.saveNotice(clubId, content, adminId);
                }
            }
            if (StringUtils.isNotBlank(qqGroup)
                    && !qqGroup.matches(Regex.qqGroup.value)) {
                errorMsg("请输入正确的车友会QQ群号", resp);
                return null;
            } else {
                club.setQqGroup(qqGroup);
            }
            club.setUpdateAt(DateUtils.getNow());
            club.setUpdateBy(adminId);
            club.setThemeId(themeId);

            long i = clubService.update(club);
            if (i < 1) {
                retMsg = "修改失败";
            }

             //跟新论坛级联关系
             List<ClubForum> listForum = clubService.getForumList(clubId);
             if (listForum != null && !listForum.isEmpty()) {
                      long result = clubService.deleteForumByClubId(clubId);
                       if (result > 0) {
                            clubService.addClubForum(club);
                        }
              } else {
                        clubService.addClubForum(club);
                    }
              }
            successMsg(retMsg, "club-detail", resp);
             return null;
    }

    /**
     * 删除论坛级联关系
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/forumDelete.do")
    public String forumDelete(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        GeliLogFacade.log();
        long clubForumId = env.paramLong("clubForumId", 0);
        long clubId = env.paramLong("clubId", 0);
//        long adminId = GeliSession.getCurrentUser().getUserId();
        long i = clubService.removeForumById(clubForumId, clubId);
        if (i == 1) {
            successMsg("删除成功", "club-detail", resp);
        } else if (i == 2) {
            errorMsg("只有一个论坛，不能删除", resp);
        } else if (i == 0) {
            errorMsg("删除失败", resp);
        }
        return null;
    }

    /**
     * 修改处理情况
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/club/updateClubDisposeStatus", method = RequestMethod.POST)
    public void updateClubDisposeStatus(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long clubId = env.paramLong("clubId", 0);
        int status = env.paramInt("status", 0);
        if (clubId < 1) {
            errorMsg("该车友会不存在", resp);
            return;
        }
        Club club = clubService.getClub(clubId);
        if (club == null) {
            errorMsg("该车友会不存在", resp);
            return;
        }
        ClubDispose clubDispose = clubService.getClubDispose(clubId);
        if (clubDispose != null) {
            if (status != clubDispose.getStatus()) {
                clubDispose.setStatus(status);
                geliDao.update(clubDispose);
            }
        } else {
            clubDispose = new ClubDispose();
            clubDispose.setClubId(clubId);
            clubDispose.setStatus(status);
            geliDao.create(clubDispose);
        }
        successMsg("修改成功", "list-club-audit", resp);
    }

    /**
     * 备注页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/editRemark", method = RequestMethod.GET)
    public String editRemark(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long clubId = env.paramLong("clubId", 0);
        Club club = clubService.getClub(clubId);
        if (club == null) {
            try {
                resp.sendError(404);
            } catch (IOException ex) {
                log.error("editRemark fail!", ex);
            }
            return null;
        }
        ClubDispose dispose = clubService.getClubDispose(clubId);
        if (dispose == null) { //当车友会没有处理记录时新建一个记录;
            long adminId = GeliSession.getCurrentUser().getUserId();
            dispose = new ClubDispose();
            dispose.setClubId(clubId);
            dispose.setCreateBy(adminId);
            dispose.setCreateAt(new Date());
            geliDao.create(dispose);
            req.setAttribute("dispose", dispose);
        }
        if (dispose.getUpdateBy() != 0) {
            try {
                GeliUser user = GeliUtils.getDao().find(GeliUser.class, dispose.getUpdateBy());
                dispose.setGeliUser(user);
            } catch (DataAccessException ex) {
                log.error("update GeliUser fail!", ex);
            }

        }
        req.setAttribute("dispose", dispose);
        req.setAttribute("clubId", clubId);
        return "admin/club/remark";
    }

    /**
     * 修改备注
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/club/updateRemark", method = RequestMethod.POST)
    public void updateRemark(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long clubId = env.paramLong("clubId", 0);
        String remark = env.param("remark", "");
        if (clubId < 1) {
            errorMsg("车友会ID错误", resp);
            return;
        }
        Club club = clubService.getClub(clubId);
        if (club == null) {
            errorMsg("车友会ID错误", resp);
            return;
        }
        if (StringUtils.isNotBlank(remark) && remark.length() > 2000) {
            errorMsg("备注字数过多", resp);
            return;
        }
        ClubDispose clubDispose = geliDao.find(ClubDispose.class, clubId);
        if (clubDispose != null) {
            long adminId = GeliSession.getCurrentUser().getUserId();
            clubDispose.setRemark(remark);
            clubDispose.setUpdateBy(adminId);
            clubDispose.setCreateAt(new Date());
            geliDao.update(clubDispose);
            successMsg("保存成功", "list-club-audit-remark", resp);
        } else {
            errorMsg("找不到该处理记录", resp);
        }
    }

    /**
     * 查询车友会信息，确认删除车友会
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/deleteClubPage.do")
    public String deleteClubPage(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        //param
        String name = env.param("name", "").trim();
        long clubId = env.paramLong("clubId", 0);
        //sql
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select * from ").appendSql(geliOrm.getTableName(Club.class)).appendSql(" where 1=1 ");
        if (clubId > 0) {
            sql.appendSql(" and club_id =").appendValue(clubId);
        } else if (StringUtils.isNotBlank(name)) {
            sql.appendSql(" and name =").appendValue(name);
        }
        Club c = null;
        ClubAddress ca = null;
        ClubDispose cd = null;
        ClubLevel level = null;
        if (clubId != 0 || StringUtils.isNotBlank(name)) {
            c = geliDao.findFirst(Club.class, sql.getSql(), sql.getValues());
            if (c != null) {
                level = clubLevelService.getById(c.getLevelId());
                ca = clubService.getAddress(c.getClubId());
                cd = clubService.getClubDispose(c.getClubId());
            }
        }
        req.setAttribute("name", name);
        req.setAttribute("clubId", clubId);
        req.setAttribute("club", c);
        req.setAttribute("clubAddress", ca);
        req.setAttribute("clubDispose", cd);
        req.setAttribute("statusDesc", Club.statusDesc);
        req.setAttribute("level", level);
        return "admin/club/deleteClubPage";
    }

    @RequestMapping(value = "/club/deleteClub.do", method = RequestMethod.POST)
    public void deleteClub(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Club club = clubService.getClub(clubId);
        if (club == null) {
            errorMsg("该车友会不存在，请先查询后再删除！", resp);
            return;
        }
        long uid = GeliSession.getCurrentUser().getUserId();
        if (clubService.deleteClub(uid, clubId)) {
            successMsg("删除成功", "page-deleteClub", resp);
        } else {
            errorMsg("删除失败，请联系开发人员！", resp);
        }
    }

    /**
     * 校验车友会认证车主人数接口 当发现数据有误时会取消车主认证,会减去相应油值
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/dev/verifyClubVip", method = RequestMethod.POST)
    public void verifyClubVip(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        int type = WebUtils.paramInt(req, "type", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        int pageSize = 20;
        try {
            if (type == 1) {//当校验所有车友会时
                //分页取出车友会列表校验

                Pager<Club> pager = clubService.listClubByStatusForPage(1, 1, pageSize);
                while (pager.getPageNo() <= pager.getPageCount()) {
                    List<Club> clubs = pager.getResultList();
                    if (clubs != null) {
                        for (Club club : clubs) {
                            verifyClubVip(club);
                        }
                    }
                    if (pager.getPageNo() < pager.getPageCount()) {
                        pager = clubService.listClubByStatusForPage(1, pager.getPageNo() + 1, pageSize);
                    } else if (pager.getPageNo() == pager.getPageCount()) {
                        break;
                    }
                }

                successMsg("操作成功", "list-verifyClubVip", resp);
            } else if (type == 2) {
                //当校验指定车友会时
                if (clubId > 0) {

                    Club club = clubService.getClub(clubId);
                    if (club == null) {
                        errorMsg("车友会ID有误", resp);
                        return;
                    }
                    verifyClubVip(club);
                }

                successMsg("操作成功", "list-verifyClubVip", resp);
            } else {
                errorMsg("参数有误", resp);
            }
        } catch (Exception ex) {
            log.error("未知异常");
            errorMsg("未知错误,请通知管理员", resp);
        }
    }

    /**
     * 校验车友会车主验证
     *
     * @param club
     */
    private void verifyClubVip(Club club) {
        if (club == null) {
            return;
        }
        List<ClubMember> clubMembers = memberService.listMemberByClubId(club.getClubId());

        if (clubMembers == null) {
            return;
        }
        for (ClubMember clubMember : clubMembers) {
            String vipInfo = memberService.getVipInfo(clubMember.getUid());
            User user = userService.findUser(clubMember.getUid());
            if (StringUtils.isNotBlank(vipInfo)) { //当用户是车主认证时
                if (user.getVip() == 0) {
                    //增加用户车主认证
                    List<ClubMember> clubList = memberService.listClubMemberByUser(user.getUid());
                    userService.setVip(user.getUid(), vipInfo);
                    for (ClubMember member : clubList) {
                        clubService.increaseVipNum(member.getClubId());

                        ClubIntegral integral = petrolService.getById(PetrolService.ADD_CLUB_PETROL_ITEM_VIP);
                        petrolService.addToClubWithinLimit(member.getClubId(), integral.getIntegralId(), integral.getPetrol(), integral.getName(), false);
                    }
                }
            } else {
                if (user.getVip() == 1) {
                    //取消用户车主认证
                    userService.cancelVip(user.getUid());
                    List<ClubMember> clubList = memberService.listClubMemberByUser(user.getUid());
                    for (ClubMember member : clubList) {
                        clubService.decreaseVipNum(member.getClubId());

                        ClubIntegral integral = petrolService.getById(PetrolService.ADD_CLUB_PETROL_ITEM_VIP_QUIT);
                        petrolService.addToClubWithinLimit(member.getClubId(), integral.getIntegralId(), integral.getPetrol(), integral.getName(), false);
                    }
                }
            }
        }
        //实时校验车友会车主认证人数
        clubService.synVipNum(club);
    }
   
}